#include "TitleScreenState.h"
#include "Overseer.h"
#include "GUIManager.h"
#include "InputManager.h"
#include "Updater.h"
#include "LoadingState.h"

TitleScreenState::TitleScreenState(Overseer *o) : State(o)
{
	name = "TitleScreen";
}

void TitleScreenState::initialise()
{
	setStatus("Initializing...");
	overseer->getGUIManager()->executeScript("titleScreen.lua");
	overseer->getInputManager()->releaseMouse();
	thread = boost::thread(&TitleScreenState::workerThread, this);
}

void TitleScreenState::pause()
{
}

void TitleScreenState::resume()
{
}

void TitleScreenState::workerThread()
{
	Updater *updater = new Updater();
	setStatus("Checking for updates...");
	int updateCode = updater->checkForUpdates();

	if (updateCode&4)
	{
		setStatus("There is a new Memory.xml available, but it's not compatible with this version of Overseer.");
	}
	else if (updateCode&1)
	{
		setStatus("New Memory.xml is available! Downloading...");
		if (updater->updateMemoryXML()) setStatus("Memory.xml has been updated!");
		else setStatus("Memory.xml update failed...");
	}
	else setStatus("Memory.xml is up to date.");

	if (updateCode&2) setStatus("New version of Overseer is available! Go download it!");
	else setStatus("Overseer is up to date.");
	overseer->changeState(new LoadingState(overseer));
}

void TitleScreenState::update(Ogre::Real timeSinceLastFrame)
{
}


void TitleScreenState::setStatus(std::string s)
{
	statusQueue.push(s);
}

std::string TitleScreenState::getStatus()
{
	boost::mutex::scoped_lock lock(statusMutex);
	if (statusQueue.size()==0) return "";
	std::string s = statusQueue.front();
	statusQueue.pop();
	return s;
}

void TitleScreenState::exit()
{
	//thread.join();
}

bool TitleScreenState::keyPressed(const OIS::KeyEvent &evt)
{
	if (evt.key==OIS::KC_ESCAPE) overseer->exit();
	return true;
}
bool TitleScreenState::keyReleased(const OIS::KeyEvent &evt)
{
	return true;
}
bool TitleScreenState::mouseMoved(const OIS::MouseEvent &evt)
{
	return true;
}
bool TitleScreenState::mousePressed(const OIS::MouseEvent &evt, OIS::MouseButtonID id)
{
	return true;
}
bool TitleScreenState::mouseReleased(const OIS::MouseEvent &evt, OIS::MouseButtonID id)
{
	return true;
}